<?php

/**
 * Created by Command.
 * User: Vito
 */

namespace app\admin\curd\room;

use app\common\curd\Index;
use think\db\Query;
use app\model\Building;

class RoomIndex extends Index
{
    /**
     * 关键词查询指定字段
     * @var string[]
     */
    protected $keywordQueryArgs = [];
    //追加标签数据
    protected $labelCallback = [
        'get_status_enum' => ['name' => '状态'],
        'building'        => ['name' => '楼房','field'=>'building'],
        'get_sex_enum' => ['name' => '性别'],
    ];
    //查询条件
    protected $where = [];
    //字段
    protected $field = [];
    //排除字段
    protected $withoutField = false;
    //关联
    protected $with = [
        'building',
        'roomType',
    ];
    protected $order = [
        'Room.id' => 'desc', 
        // 'Room.status' => 'desc'
    ];
    /**
     * 需要查询条件的字段
     * 数据库字段和参数字段名不一样 'db_field' => 'param_field'
     * 数据库字段和参数字段名一样 'field'
     * @var array
     */
    protected $queryField = [];
    protected $middleware = [
        'middleWhere'
    ];
    protected function middleWhere($next)
    {
        $kw = $this->request['kw'];
        $type = $this->request['type'];
        if ($kw) {
            $this->field =
                [
                    'Building.id' => 'building_id',
                    'RoomType.id' => 'room_type_id',
                    'Room.building_number' => 'building_number',
                    'Room.*'
                ];
        }
        if ($type == 'valid') {
            $this->field =
                [
                    'Building.id' => 'building_id',
                    'RoomType.id' => 'room_type_id',
                    'Room.building_number' => 'building_number',
                    'Room.*'
                ];
        }

        return $next();
    }
    protected function queryCallback(Query $query)
    {
        // halt($this->request);
        $kw = $this->request['kw'];
        $type = $this->request['type'];
        if ($kw) {
            $query
                ->join('wuye_room_type RoomType', 'RoomType.id = Room.room_type', 'right')
                ->join('wuye_building Building', 'Building.id = Room.building_number', 'right')
                ->where('Building.name|RoomType.name', 'like', '%' . $kw . '%');
        }
        if ($type == 'valid') {
            // $where['RoomType.live_number'] = ['>', 'Room.use_people'];
            $query
                ->join('wuye_room_type RoomType', 'RoomType.id = Room.room_type', 'right')
                ->join('wuye_building Building', 'Building.id = Room.building_number', 'right')
                ->where('RoomType.live_number > Room.use_people');
        }
    }

    public function building(){
        $res = Building::select();
        $arr = [];
        foreach ($res as $key => $value) {
            # code...
            $arr[$value['id']] = $value['name']. $value['building_number'];
        }
        return $arr;
    }
}
